import Cookies from 'js-cookie'
import getToken from './getToken'
// 判断token是否存在或者过期,不存在或者过期重新请求token，并且返回token
async function judgeTokenAccess () {
  let cookie = Cookies.getJSON('token')
  if (!cookie || judgeTokenExpires(cookie)) {
    let data = await getToken()
    let token = data.access_token
    let expires = data.expires_in
    // 过期时间2小时
    let inFifteenMinutes = new Date(new Date().getTime() + 2 * 60 * 60 * 1000)
    Cookies.set('token', {
      token: token,
      expires: expires,
      preDate: new Date().getTime()
    }, { expires: inFifteenMinutes })
    return token
  }
  return cookie.token
}

// 判断token过期函数
function judgeTokenExpires (cookie) {
  let curDate = new Date().getTime()
  let preDate = cookie.preDate
  let expires = cookie.expires
  if (curDate >= preDate + (expires * 1000) - (60 * 1000)) {
    // 过期
    return true
  } else {
    // 未过期
    return false
  }
}

// 设置登录信息
function setLoginCookie (data) {
  Cookies.set('login', data)
}

// 设置登录信息
function getLoginCookie () {
  let login = Cookies.get('login')
  if (login) {
    login = JSON.parse(login)
  } else {
    login = null
  }
  return login
}

// 删除登录信息
function removeLoginCookie () {
  Cookies.remove('login')
}

export { judgeTokenAccess, setLoginCookie, getLoginCookie, removeLoginCookie }
